<template>
  <div class="dialog">
    <el-dialog
      :title="'数据项配置'+titleText"
      :visible.sync="showDialog"
      width="50%"
      top="0"
      :close-on-click-modal="false"
      @close="cancel"
    >
      <el-form
        ref="ruleForm"
        label-position="left"
        :model="formData"
        :rules="rules"
        class="el-form"
      >
        <el-form-item label="选择工程项目:" prop="rtuNo" class="w100p">
          <el-cascader
            :options="options"
            :props="{ expandTrigger: 'hover',value: 'companyMark',children:'child',label:'ownershipName', checkStrictly: true, }"
            clearable
            @change="ownership"
          />
        </el-form-item>
        <el-form-item label="数据项选择:" prop="dataItemId" class="w100p">
          <el-select
            v-model="formData.dataItemId"
            placeholder="请选择数据项"
            filterable
            clearable
            @change="depDataItem"
          >
            <el-option
              v-for="(item,index) in dataItemList"
              :key="index+'dataItemId'"
              :label="item.dataItemName"
              :value="item.dataItemId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="展示数据项名称:" prop="dataItemName" class="w100p">
          <el-input v-model="formData.dataItemName" placeholder clearable />
        </el-form-item>
        <el-form-item label="原始名称:" prop="originalName" class="w100p">
          <el-input
            v-model="formData.originalName"
            placeholder
            disabled
            clearable
          />
        </el-form-item>
        <el-form-item label="是否可展示:" prop="visible" class="w100p">
          <el-select
            v-model="formData.visible"
            placeholder="请选择是否可展示"
            filterable
            clearable
          >
            <el-option
              v-for="item in yesornoList"
              :key="item.name"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否可控:" prop="control" class="w100p">
          <el-select
            v-model="formData.control"
            placeholder="请选择是否可控"
            filterable
            clearable
          >
            <el-option
              v-for="item in yesornoList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="单位:" prop="identificationNumber" class="w100p">
          <el-select
            v-model="formData.unitNo"
            placeholder="请选择单位"
            filterable
            clearable
          >
            <el-option
              v-for="item in unitList"
              :key="item.unitNo"
              :label="item.unitName"
              :value="item.unitNo"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button type="primary" class="savebtn" @click="save('ruleForm')">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dataItemManageApi from "@/api/basic-info-manage/data-item-manage";
import Axios from "axios";

export default {
  name: "",
  components: {},
  props: {
    // 弹框名称
    titleText: {
      type: String,
      default: "",
    },
    nowChanceStau: {
      type: String,
      default: "",
    },
    show: {
      type: Boolean,
      default: false,
    },
    editObject: {
      type: [Object],
      default: () => {
        return {};
      },
    },
    unitList: {
      type: [Array],
      default: () => {
        return [];
      },
    },
  },
  data() {
    return {
      formData: {},
      rules: {
        dataItemId: [
          {
            required: true,
            message: "请选择数据项",
            trigger: ["change", "blur"],
          },
        ],
      },
      showDialog: this.show,
      yesornoList: [
        { name: "是", value: true },
        { name: "否", value: false },
      ],
      dataItemList: [],
      dataTreeItemList: [],
      options: [],
      ownershiptext: [],
    };
  },
  computed: {},
  watch: {
    show(v) {
      this.showDialog = v;
    },
    nowChanceStau(v) {
      if (v === "add") {
        this.formData = {};
        this.dataItemList = [];
        if (this.ownershiptext&&this.ownershiptext.length > 0) {
          this.ownership(this.ownershiptext);
        }
      }
      if (v === "edit") {
        this.formData = this.editObject;
        this.dataItemList = [
          {
            dataItemId: this.editObject.dataItemId,
            dataItemName: this.editObject.dataItemName,
            dataType: {
              dataTypeId: this.editObject.dataTypeId,
              dataTypeName: this.editObject.dataTypeName,
              mainingControlType: this.editObject.mainingControlType,
              enumListType: this.editObject.enumListType || "",
            },
            dataTypeId: this.editObject.dataTypeId,
          },
        ];
      }
    },
  },
  created() {},
  mounted() {
    this.queryOrganizationNo();
  },
  methods: {
    queryOrganizationNo() {
      Axios({
        // url: `https://tdiot.cloud/iotApplication/ownership/queryTreeByCompanyMark?companyMark=HuZhouHengXin`,
        // url:  `https://tdiot.cloud/iotApplication/ownership/queryTreeByCompanyMark?companyMark=${sessionStorage.organizationNo}`,
        // url:   this.$baseurl.webServiceUrl + `v3/iotsheep/iotPlatform/queryTreeByCompanyMark?companyMark=${sessionStorage.organizationNo}`,
        url:   this.$baseurl.cloudBaseurl + `iotApplication/ownership/queryTreeByCompanyMark?companyMark=${sessionStorage.organizationNo}`,
        method: "get",
      }).then((res) => {
        if (res.data.code === 1) {
          this.dataTreeItemList = [res.data?.data] || [];
          this.options = this.filterArrForKey(this.dataTreeItemList);
        } else {
          this.$message.warning("查询失败！");
        }
      });
    },
    // 循环过滤树形数组
    filterArrForKey(arr, child = "child") {
      let newArr = [];
      if (arr === []) {
        return;
      }
      console.log("filterArrForKey", arr);
      newArr = arr.map((item) => {
        if (item[child].length > 0) {
          item = {
            ...item,
            child: this.filterArrForKey2(item[child]),
          };
        } else {
          delete item[child];
        }
        return item;
      });
      newArr = newArr.filter((item) => item != null);
      return newArr;
    },
    depDataItem(e) {
      let index = this.dataItemList.findIndex((b) => b.dataItemId === e);
      let form = { ...this.dataItemList[index] };
      this.$set(this.formData, "category", "STATE");
      this.$set(this.formData, "dataItemName", form.dataItemName);
      this.$set(this.formData, "dataTypeId", form.dataTypeId);
      this.$set(
        this.formData,
        "dataTypeName",
        form.dataType ? form.dataType.dataTypeName : ""
      );
      this.$set(
        this.formData,
        "mainingControlType",
        form.dataType ? form.dataType.mainingControlType : ""
      );
      this.$set(
        this.formData,
        "enumListType",
        form.dataType ? form.dataType.enumListType : ""
      );
      this.$set(this.formData, "originalName", form.dataItemName);
    },
    ownership(e) {
      if (e) {
        let text = e.slice(-1);
        this.ownershiptext = e;
        dataItemManageApi.getDataItemByList(text[0]).then((res) => {
          let data = res.data || [];
          this.dataItemList = data;
          this.$set(this.formData, "rtuNo", "");
          this.$set(this.formData, "deviceName", "");
        });
      }
    },
    save(formData) {
      this.$refs[formData].validate((valid) => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            dataItemManageApi.edit(this.formData).then((res) => {
              if (res.code === 1) {
                this.$message.success("修改成功！");
                this.close();
              } else {
                this.$message.error(res.msg);
              }
            });
          } else if (this.nowChanceStau === "add") {
            this.formData.organizationNo = sessionStorage.organizationNo;
            dataItemManageApi.add(this.formData).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg);
                this.close();
              } else {
                this.$message.error(res.msg);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    close() {
      this.$emit("closeDialog");
    },
    cancel() {
      this.$emit("cancelDialog");
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-form-item__content {
  display: inline-block !important;
}
</style>
